#include "usmart_fifo.h"


void fifo_init(fifo_t *fifo, uint8_t *array, uint16_t deepth)
{
		if(!fifo || !array) { return;};
		
    fifo->deepth = deepth;
    fifo->occupy = 0;
    fifo->array = array;
    fifo->limit = array + deepth;
    fifo->wp = fifo->array;
    fifo->rp = fifo->array;
}

void reset_fifo(fifo_t *fifo)
{
		if(!fifo) return;
    fifo->occupy = 0;
    fifo->rp = fifo->array;
    fifo->wp = fifo->array;
}

uint8_t write_fifo(fifo_t *fifo, uint8_t ch)
{
		if(!fifo) return 0;
    if (fifo->occupy >= fifo->deepth) 
		{
        return 0;
    }
    
    *fifo->wp++ = ch;
    
    if (fifo->wp >= fifo->limit) fifo->wp = fifo->array;
    
		//use os,must lock
    fifo->occupy++;
    
    return 1;
}

uint8_t write_fifos(fifo_t *fifo, uint8_t *ch, uint16_t size)
{
		if(!fifo) return 0;
    if (size > fifo->deepth - fifo->occupy) return 0;
    
    for (; size > 0; size--) 
	  {
        *fifo->wp++ = *ch++;
        if (fifo->wp >= fifo->limit) fifo->wp = fifo->array;
        
				//use os,must lock
        fifo->occupy++;
    }
    
    return 1;
}

uint8_t read_fifo(fifo_t *fifo, uint8_t *ch) 
{
    if(!fifo) return 0;    
    if (fifo->occupy == 0) return 0;  
    
    *ch = *fifo->rp++;
    if (fifo->rp >= fifo->limit) fifo->rp = fifo->array;
    
		//use os,must lock
    fifo->occupy--;
    
    return 1;
}

uint8_t read_fifos(fifo_t *fifo, uint8_t *ch, uint16_t size) 
{
    uint16_t i;
    if(!fifo) return 0;    
    if (fifo->occupy < size) return 0;  

    for (i=0; i<size; i++)
	  {
        *(ch+i) = *fifo->rp++;
        if (fifo->rp >= fifo->limit) fifo->rp = fifo->array;
        
        //OS_ENTER_CRITICAL();
        fifo->occupy--;
        //OS_EXIT_CRITICAL();        
    }
    
    return 1;
}

uint8_t is_fifo_empty(fifo_t *fifo)
{
		if(!fifo) return 0;
    if (fifo->occupy == 0) return 1;
    else return 0;
}

uint8_t is_fifo_full(fifo_t *fifo)
{
		if(!fifo) return 0;
    if (fifo->occupy == fifo->deepth) return 1;
    else return 0;
}















